{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "from operator import itemgetter\n",
    "\n",
    "\n",
    "K=3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [],
   "source": [
    "data=[\n",
    "    ['A','a',5],\n",
    "    ['A','b',3],\n",
    "    ['A','c',4],\n",
    "    ['A','d',4],\n",
    "    ['B','a',3],\n",
    "    ['B','b',1],\n",
    "    ['B','c',2],\n",
    "    ['B','d',2],\n",
    "    ['B','e',2],\n",
    "    ['C','a',4],\n",
    "    ['C','b',4],\n",
    "    ['C','c',4],\n",
    "    ['C','d',4],\n",
    "    ['C','e',4],\n",
    "    ['D','a',3],\n",
    "    ['D','b',2],\n",
    "    ['D','c',2],\n",
    "    ['D','e',3],\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'A': {'a': 5, 'b': 3, 'c': 4, 'd': 4},\n",
       " 'B': {'a': 3, 'b': 1, 'c': 2, 'd': 2, 'e': 2},\n",
       " 'C': {'a': 4, 'b': 4, 'c': 4, 'd': 4, 'e': 4},\n",
       " 'D': {'a': 3, 'b': 2, 'c': 2, 'e': 3}}"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "train_data = {}\n",
    "\n",
    "for user, item,record in data:\n",
    "    train_data.setdefault(user,{})\n",
    "    train_data[user][item] = record\n",
    "\n",
    "train_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'a': 4, 'b': 4, 'c': 4, 'd': 3, 'e': 3}"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 计算每个物品被用户评分的个数\n",
    "item_cnt = {}\n",
    "for user, items in train_data.items():\n",
    "    for i in items:\n",
    "        # count item popularity\n",
    "        item_cnt.setdefault(i, 0)\n",
    "        item_cnt[i] += 1\n",
    "item_cnt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'a': 3.75, 'b': 2.5, 'c': 3.0, 'd': 3.333333333333333, 'e': 3.0}"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 计算每个项目的平均评分\n",
    "average_rating = {}\n",
    "for user, items in train_data.items():\n",
    "    for i in items:\n",
    "        average_rating.setdefault(i, 0)\n",
    "        average_rating[i] += train_data[user][i] / item_cnt[i]\n",
    "average_rating"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'A': 4.0, 'B': 2.0, 'C': 4.0, 'D': 2.5}"
      ]
     },
     "execution_count": 50,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 计算用户的平均评分\n",
    "user_average_rating={}\n",
    "for user, items in train_data.items():\n",
    "    user_average_rating.setdefault(user, 0)\n",
    "    for i in items:\n",
    "        user_average_rating[user] += train_data[user][i] / len(train_data[user])\n",
    "user_average_rating"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 修正后的余弦相似度\n",
    "def calCosineSimi():\n",
    "    C2 = dict()\n",
    "    C3 = dict()\n",
    "    C1 = dict()\n",
    "    for user, items in train_data.items():\n",
    "        for i in items:\n",
    "            for j in items:\n",
    "                if i == j:\n",
    "                    continue\n",
    "                C1.setdefault(i, {})\n",
    "                C1[i].setdefault(j, 0)\n",
    "                C2.setdefault(i, {})\n",
    "                C2[i].setdefault(j, 0)\n",
    "                C3.setdefault(i, {})\n",
    "                C3[i].setdefault(j, 0)\n",
    "                C1[i][j] += ((train_data[user][i] - user_average_rating[user]) * (\n",
    "                        train_data[user][j] - user_average_rating[user]))\n",
    "                C2[i][j] += ((train_data[user][i] - user_average_rating[user]) * (\n",
    "                        train_data[user][i] -user_average_rating[user]))\n",
    "                C3[i][j] += ((train_data[user][j] - user_average_rating[user]) * (\n",
    "                        train_data[user][j] - user_average_rating[user]))\n",
    "    # 计算最终的物品相似度矩阵\n",
    "    item_sim = dict()\n",
    "    for i, related_items in C1.items():\n",
    "        item_sim[i] = {}\n",
    "        for j, cuv in related_items.items():\n",
    "            if C1[i][j] == 0:\n",
    "                item_sim[i][j] = 0\n",
    "            else:\n",
    "                item_sim[i][j] = C1[i][j] / math.sqrt(C2[i][j] * C3[i][j])\n",
    "    return item_sim"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 皮尔逊相似度\n",
    "def calPearsonSimi():\n",
    "    C2 = dict()\n",
    "    C3 = dict()\n",
    "    C1 = dict()\n",
    "    for user, items in train_data.items():\n",
    "        for i in items:\n",
    "            for j in items:\n",
    "                if i == j:\n",
    "                    continue\n",
    "                C1.setdefault(i, {})\n",
    "                C1[i].setdefault(j, 0)\n",
    "                C2.setdefault(i, {})\n",
    "                C2[i].setdefault(j, 0)\n",
    "                C3.setdefault(i, {})\n",
    "                C3[i].setdefault(j, 0)\n",
    "\n",
    "                C1[i][j] += ((train_data[user][i] -average_rating[i]) * (\n",
    "                        train_data[user][j] - average_rating[j]))\n",
    "                C2[i][j] += ((train_data[user][i] - average_rating[i]) * (\n",
    "                        train_data[user][i] - average_rating[i]))\n",
    "                C3[i][j] += ((train_data[user][j] - average_rating[j]) * (\n",
    "                       train_data[user][j] - average_rating[j]))\n",
    "\n",
    "    # 计算最终的物品相似度矩阵\n",
    "    item_sim = dict()\n",
    "    for i, related_items in C1.items():\n",
    "        item_sim[i] = {}\n",
    "        for j, cuv in related_items.items():\n",
    "            if C1[i][j] == 0:\n",
    "                item_sim[i][j] = 0\n",
    "            else:\n",
    "                item_sim[i][j] = C1[i][j] / math.sqrt(C2[i][j] * C3[i][j])\n",
    "    return item_sim"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [],
   "source": [
    "def predict(item_sim,user, item):\n",
    "    rui = 0\n",
    "    # 分子和分母\n",
    "    C1 = 0\n",
    "    C2 = 0\n",
    "    if not item in item_sim:\n",
    "        return rui\n",
    "    for interacted_item in train_data[user]:\n",
    "        simi_items=sorted(item_sim[interacted_item].items(),key=itemgetter(1), reverse=True)[:K]\n",
    "        for similar_item, similarity_factor in simi_items:\n",
    "            if item == similar_item:\n",
    "                C1 += similarity_factor*train_data[user][interacted_item]\n",
    "                C2 += math.fabs(similarity_factor)\n",
    "    if not C1 == 0:\n",
    "        rui = (C1 / C2)\n",
    "    return rui   "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'a': {'b': -1.0, 'c': -0.3333333333333333, 'd': 0, 'e': 0.4472135954999579},\n",
       " 'b': {'a': -1.0, 'c': 0.3333333333333333, 'd': 0, 'e': -0.4472135954999579},\n",
       " 'c': {'a': -0.3333333333333333, 'b': 0.3333333333333333, 'd': 0, 'e': -1.0},\n",
       " 'd': {'a': 0, 'b': 0, 'c': 0, 'e': 0},\n",
       " 'e': {'a': 0.4472135954999579, 'b': -0.4472135954999579, 'c': -1.0, 'd': 0}}"
      ]
     },
     "execution_count": 54,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 余弦相似度\n",
    "user_sim1=calCosineSimi()\n",
    "user_sim1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'a': {'b': 0.674199862463242,\n",
       "  'c': 0.9045340337332909,\n",
       "  'd': 0.828078671210825,\n",
       "  'e': 0.6488856845230502},\n",
       " 'b': {'a': 0.674199862463242,\n",
       "  'c': 0.8944271909999159,\n",
       "  'd': 0.936585811581694,\n",
       "  'e': 0.9733285267845753},\n",
       " 'c': {'a': 0.9045340337332909,\n",
       "  'b': 0.8944271909999159,\n",
       "  'd': 0.9428090415820634,\n",
       "  'e': 0.8164965809277261},\n",
       " 'd': {'a': 0.828078671210825,\n",
       "  'b': 0.936585811581694,\n",
       "  'c': 0.9428090415820634,\n",
       "  'e': 0.948683298050514},\n",
       " 'e': {'a': 0.6488856845230502,\n",
       "  'b': 0.9733285267845753,\n",
       "  'c': 0.8164965809277261,\n",
       "  'd': 0.948683298050514}}"
      ]
     },
     "execution_count": 55,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 皮尔逊相似度\n",
    "user_sim2=calPearsonSimi()\n",
    "user_sim2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1.0000000000000002"
      ]
     },
     "execution_count": 56,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 使用余弦相似度进行推荐\n",
    "predict(user_sim1,'A','e')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3.4935886896179276"
      ]
     },
     "execution_count": 57,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 使用皮尔逊相似度进行推荐\n",
    "predict(user_sim2,'A','e')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
